package com.colorfruit.admin.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.colorfruit.admin.business.dao.*;
import com.colorfruit.admin.business.service.ProductService;
import com.colorfruit.admin.pojo.constant.AliConstant;
import com.colorfruit.admin.pojo.constant.CommonConstant;
import com.colorfruit.admin.pojo.entity.*;
import com.colorfruit.admin.pojo.enums.ErrorCodeEnum;
import com.colorfruit.admin.pojo.enums.OrderStatus;
import com.colorfruit.admin.pojo.enums.StatusEnum;
import com.colorfruit.admin.pojo.vo.preonshelf.CountPriceVo;
import com.colorfruit.admin.pojo.vo.preonshelf.PreOnShelfVo;
import com.colorfruit.admin.pojo.vo.prepurchase.*;
import com.colorfruit.admin.pojo.vo.product.FoundationProductVo;
import com.colorfruit.admin.pojo.vo.product.ProductTree;
import com.colorfruit.framework.common.util.BusinessUtil;
import com.colorfruit.framework.common.util.DataConvertUtil;
import com.colorfruit.framework.common.util.DataValidateUtil;
import com.colorfruit.framework.model.admin.CommonDate;
import com.colorfruit.framework.model.pojo.BaseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    FoundationSysUserMapper foundationSysUserMapper; //用户表

    @Autowired
    FoundationProductMapper foundationProductMapper; //商品表

    @Autowired
    PrePurchaseOrderMapper prePurchaseOrderMapper; //预采购订单表

    @Autowired
    PreShelfOrderMapper preShelfOrderMapper; //预上架订单表

    @Autowired
    ConfigCommonMapper configCommonMapper;//通用配置表

    @Autowired
    StatisticProductMapper statisticProductMapper;//商品统计表

    @Autowired
    GlobalProcessionControlMapper globalProcessionControlMapper;

    @Override
    public BaseResult insertProduct(FoundationProductVo foundationProductVo) {
        try {
            log.info("[service] [IN] insertProductBasic param : {}", foundationProductVo.toString());
            //1. 校验商品信息
            if (!DataValidateUtil.verifyString(foundationProductVo.getProductName())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品名称不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getProductSpecifications())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品规格不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getProductPlace())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品产地不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getProductVariety())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品品种不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getProductType())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品类别不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getPackageType())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品包装类别不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getPackageVolume())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品包装体积不能为空");
            }
            if (foundationProductVo.getProductGrossWeight() == null) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品毛重不能为空");
            }
            if (foundationProductVo.getProductNetWeight() == null) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品净重不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getProductSmallPic())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品小图不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getProductBigPic())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品大图不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getDescriptionPics())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品描述图不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProductVo.getProductLevel())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品等级不能为空");
            }
            FoundationProduct foundationProduct = new FoundationProduct();
            BeanUtils.copyProperties(foundationProductVo, foundationProduct);

            FoundationProduct product = foundationProductMapper.getProductByNineCondition(foundationProduct);
            if (product != null) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品已存在, 请勿重复添加");
            }
            //2. 插入商品
            foundationProduct.setProductSmallPic(AliConstant.DOMAIN + AliConstant.IMAGE + foundationProduct.getProductSmallPic());
            foundationProduct.setProductBigPic(AliConstant.DOMAIN + AliConstant.IMAGE + foundationProduct.getProductBigPic());
            String descriptionPics = foundationProduct.getDescriptionPics();
            String[] descripPicArray = descriptionPics.split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < descripPicArray.length; i++) {
                String url = AliConstant.DOMAIN + AliConstant.IMAGE + descripPicArray[i];
                stringBuffer.append(url);
                if (i != descripPicArray.length - 1) {
                    stringBuffer.append(",");
                }
            }
            foundationProduct.setDescriptionPics(stringBuffer.toString());
            foundationProduct.setRecordStatus(StatusEnum.EFFECTIVE_STATUS.getStatusCode());
            foundationProduct.setMarketMonth(foundationProductVo.getMarketMonth());
            foundationProduct.setCreateTime(new Date());
            foundationProduct.setUpdateTime(new Date());
            int insert = foundationProductMapper.insertSelective(foundationProduct);
            //3. 商品统计信息初始化
            StatisticProduct statisticProduct = new StatisticProduct();
            statisticProduct.setProductId(foundationProduct.getId());
            statisticProduct.setUpdateTime(new Date());
            statisticProduct.setCreateTime(new Date());
            statisticProductMapper.insertSelective(statisticProduct);
            log.info("[service] [OUT] insertProductBasic success : {}", insert);
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public String selectTwoLevelProductList(String productName) {
        try {
            log.info("[service] [IN] selectTwoLevelProductList param : productName = {}", productName);
            List<FoundationProduct> foundationProducts = foundationProductMapper.selectAllProduct(productName);
            List<ProductTree> productTrees = new ArrayList<>();
            //数据库拿到的所有产品池
            for (FoundationProduct foundationProduct : foundationProducts) {
                //需要丢到的产品池
                Iterator<ProductTree> iterator = productTrees.iterator();
                boolean canMatch = false;
                while (iterator.hasNext()) {
                    ProductTree productTree = iterator.next();
                    if (productTree.getProductName().equals(foundationProduct.getProductName())) {
                        canMatch = true;
                        productTree.getFoundationProductList().add(foundationProduct);
                    }
                }
                if (!canMatch) {
                    ProductTree productTree = new ProductTree();
                    productTree.setProductName(foundationProduct.getProductName());
                    productTree.getFoundationProductList().add(foundationProduct);
                    productTrees.add(productTree);
                }
            }
            String productJson = JSON.toJSONString(productTrees);
            log.info("[service] [OUT] selectTwoLevelProductList success productJson= {}", productJson);
            return productJson;
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult getProductEditInfo(Long productId) {
        try {
            log.info("[service] [IN] selectTwoLevelProductList param : productId = {}", productId);
            FoundationProduct foundationProduct = foundationProductMapper.selectByPrimaryKey(productId);
            log.info("[service] [OUT] getProductEditInfo success ");
            return new BaseResult(foundationProduct);
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult editProduct(FoundationProduct foundationProduct) {
        try {
            log.info("[service] [IN] editProduct param : foundationProduct = {}", foundationProduct.toString());
            //校验
            if (!DataValidateUtil.verifyString(foundationProduct.getProductName())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品名称不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProduct.getProductSpecifications())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品规格不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProduct.getProductPlace())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品产地不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProduct.getProductVariety())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品品种不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProduct.getProductType())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品类别不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProduct.getPackageType())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品包装类别不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProduct.getPackageVolume())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品包装体积不能为空");
            }
            if (foundationProduct.getProductGrossWeight() == null) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品毛重不能为空");
            }
            if (foundationProduct.getProductNetWeight() == null) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品净重不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProduct.getProductSmallPic())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品小图不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProduct.getProductBigPic())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品大图不能为空");
            }
            if (!DataValidateUtil.verifyString(foundationProduct.getDescriptionPics())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "商品描述图不能为空");
            }
            //图片处理
            if (!foundationProduct.getProductSmallPic().contains(AliConstant.DOMAIN)) {
                foundationProduct.setProductSmallPic(AliConstant.DOMAIN + AliConstant.IMAGE + foundationProduct.getProductSmallPic());
            }
            if (!foundationProduct.getProductBigPic().contains(AliConstant.DOMAIN)) {
                foundationProduct.setProductBigPic(AliConstant.DOMAIN + AliConstant.IMAGE + foundationProduct.getProductBigPic());
            }
            String descriptionPics = foundationProduct.getDescriptionPics();
            StringBuffer stringBuffer = new StringBuffer();
            String[] descriptionPicArray = descriptionPics.split(",");
            for (int i = 0; i < descriptionPicArray.length; i++) {
                if (descriptionPicArray[i].contains(AliConstant.DOMAIN)) {
                    stringBuffer.append(descriptionPicArray[i]);
                } else {
                    String url = AliConstant.DOMAIN + AliConstant.IMAGE + descriptionPicArray[i];
                    stringBuffer.append(url);
                }
                if (i < descriptionPicArray.length - 1) {
                    stringBuffer.append(",");
                }
            }
            foundationProduct.setDescriptionPics(stringBuffer.toString());
            foundationProductMapper.updateByPrimaryKeySelective(foundationProduct);
            log.info("[service] [OUT] editProduct success foundationProduct= {}", foundationProduct);
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult deleteProduct(Long id) {
        try {
            log.info("[service] [IN] deleteProduct param : id = {}", id);
            foundationProductMapper.updateRecordStatus(id, StatusEnum.CANCELLATION_STATUS.getStatusCode());
            log.info("[service] [OUT] deleteProduct success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult insertPrePurchaseOrder(PrePurchaseOrderVo prePurchaseOrderVo) {
        try {
            log.info("[service] [IN] insertPrePurchaseOrder param : prePurchaseOrderVo = {}", prePurchaseOrderVo.toString());
            if (prePurchaseOrderVo.getProductId() == null || prePurchaseOrderVo.getProductId() == 0) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "关联商品ID不能为空");
            }
            if (prePurchaseOrderVo.getWholeNum() == null || prePurchaseOrderVo.getWholeNum() == 0) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "整采数量不能为空");
            }
            if (prePurchaseOrderVo.getWholePrice() == null) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "整采价格不能为空");
            }
            if (prePurchaseOrderVo.getZeroPrice() == null) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "零采价格不能为空");
            }
            if (prePurchaseOrderVo.getCouldPurchaseNum() == null && prePurchaseOrderVo.getCouldPurchaseNum() == 0) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "可采数量不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getActualPicUrl())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "实拍图片不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getActualVedioUrl())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "实拍视频不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getPurchaseStartTime())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "采购开始时间不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getPurchaseEndTime())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "采购结束时间不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getSupplierName())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "供应商名称");
            }
            GlobalProcessionControl globalProcessionControl = globalProcessionControlMapper.getRecentProcession();

            PrePurchaseOrder prePurchaseOrder = new PrePurchaseOrder();
            BeanUtils.copyProperties(prePurchaseOrderVo, prePurchaseOrder);
            prePurchaseOrder.setPurchaseStartTime(DataConvertUtil.StringToDateWithFormat(prePurchaseOrderVo.getPurchaseStartTime(), CommonConstant.DATE_FORMAT));
            prePurchaseOrder.setPurchaseEndTime(DataConvertUtil.StringToDateWithFormat(prePurchaseOrderVo.getPurchaseEndTime(), CommonConstant.DATE_FORMAT));
            prePurchaseOrder.setCreateTime(new Date());
            prePurchaseOrder.setUpdateTime(new Date());

            String actualPicUrl = prePurchaseOrder.getActualPicUrl();
            String[] actualPicArray = actualPicUrl.split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0 ; i < actualPicArray.length; i++){
                String image = AliConstant.DOMAIN + AliConstant.IMAGE + actualPicArray[i];
                stringBuffer.append(image);
                if (i < actualPicArray.length -1){
                    stringBuffer.append(",");
                }
            }
            prePurchaseOrder.setActualPicUrl(stringBuffer.toString());
            prePurchaseOrder.setActualVedioUrl(AliConstant.DOMAIN + AliConstant.VEDIO + prePurchaseOrder.getActualVedioUrl());
            prePurchaseOrder.setRecordStatus(OrderStatus.NOT_AUDIT.getCode());
            prePurchaseOrder.setGlobalControlId(globalProcessionControl.getId());
            prePurchaseOrderMapper.insert(prePurchaseOrder);
            log.info("[service] [OUT] insertPrePurchaseOrder success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public String selectTwoLevelPrePurchaseList(String userId, String productName, Byte recordStatus) {
        try {
            log.info("[service] [IN] insertPrePurchaseOrder param : userId = {}, productName = {}, recordStatus = {}"
                    , userId, productName, recordStatus);
            Date date = new Date();
            Date theDayBegin = DataConvertUtil.getTheDayBegin(date);
            Date theDayEnd = DataConvertUtil.getTheDayEnd(date);
            GlobalProcessionControl globalProcessionControl = globalProcessionControlMapper.getRecentProcession();
            FoundationSysUser foundationSysUser = foundationSysUserMapper.selectByPrimaryKey(userId);
            Long roleId = foundationSysUser.getRoleId();
            List<PrePurchaseOrder> prePurchaseOrders = null;
            if (roleId >= 10) {
                prePurchaseOrders = prePurchaseOrderMapper.selectTheDayPrePurchaseOrderList(recordStatus, globalProcessionControl.getId(), null);
            } else {
                prePurchaseOrders = prePurchaseOrderMapper.selectTheDayPrePurchaseOrderList(recordStatus, globalProcessionControl.getId(), userId);
            }
            List<PrePurchaseTree> prePurchaseTreeList = new ArrayList<>();
            for (PrePurchaseOrder prePurchaseOrder : prePurchaseOrders) {
                Long productId = prePurchaseOrder.getProductId();
                String purchasePersonId = prePurchaseOrder.getPurchasePersonId();
                FoundationSysUser purchaseUser = foundationSysUserMapper.selectByPrimaryKey(purchasePersonId);
                FoundationProduct foundationProduct = foundationProductMapper.selectByPrimaryKey(productId);
                //需要丢到的产品池
                Iterator<PrePurchaseTree> iterator = prePurchaseTreeList.iterator();
                boolean canMatch = false;
                while (iterator.hasNext()) {
                    PrePurchaseTree prePurchaseTree = iterator.next();
                    if (prePurchaseTree.getProductName().equals(foundationProduct.getProductName())) {
                        canMatch = true;
                        PrePurchaseOrderDetailVo prePurchaseOrderDetailVo = new PrePurchaseOrderDetailVo();
                        //将商品数据丢到模型里
                        BeanUtils.copyProperties(foundationProduct, prePurchaseOrderDetailVo);
                        log.info("加入商品数据prePurchaseOrderDetailVo = {}", prePurchaseOrderDetailVo);
                        //将预采购数据丢到模型里
                        BeanUtils.copyProperties(prePurchaseOrder, prePurchaseOrderDetailVo);
                        log.info("加入预采购数据prePurchaseOrderDetailVo = {}", prePurchaseOrderDetailVo);
                        prePurchaseOrderDetailVo.setPurchasePersonName(purchaseUser.getWxNick());
                        prePurchaseOrderDetailVo.setPurchaseStartTime(DataConvertUtil.dataToStringWithFormat(prePurchaseOrder.getPurchaseStartTime(), CommonConstant.DATE_FORMAT));
                        prePurchaseOrderDetailVo.setPurchaseEndTime(DataConvertUtil.dataToStringWithFormat(prePurchaseOrder.getPurchaseEndTime(), CommonConstant.DATE_FORMAT));
                        List<PrePurchaseOrderDetailVo> prePurchaseOrderDetailVoList = prePurchaseTree.getPrePurchaseOrderDetailVoList();
                        prePurchaseOrderDetailVo.setPriority((byte)(prePurchaseOrderDetailVoList.size() + 1));
                        prePurchaseTree.getPrePurchaseOrderDetailVoList().add(prePurchaseOrderDetailVo);
                    }
                }
                if (!canMatch) {
                    PrePurchaseTree prePurchaseTree = new PrePurchaseTree();
                    prePurchaseTree.setProductName(foundationProduct.getProductName());
                    PrePurchaseOrderDetailVo prePurchaseOrderDetailVo = new PrePurchaseOrderDetailVo();
                    //将商品数据丢到模型里
                    BeanUtils.copyProperties(foundationProduct, prePurchaseOrderDetailVo);
                    log.info("加入商品数据prePurchaseOrderDetailVo = {}", prePurchaseOrderDetailVo);
                    //将预采购数据丢到模型里
                    BeanUtils.copyProperties(prePurchaseOrder, prePurchaseOrderDetailVo);
                    log.info("加入预采购数据prePurchaseOrderDetailVo = {}", prePurchaseOrderDetailVo);
                    prePurchaseOrderDetailVo.setPurchasePersonName(purchaseUser.getWxNick());
                    prePurchaseOrderDetailVo.setPurchaseStartTime(DataConvertUtil.dataToStringWithFormat(prePurchaseOrder.getPurchaseStartTime(), CommonConstant.DATE_FORMAT));
                    prePurchaseOrderDetailVo.setPurchaseEndTime(DataConvertUtil.dataToStringWithFormat(prePurchaseOrder.getPurchaseEndTime(), CommonConstant.DATE_FORMAT));
                    List<PrePurchaseOrderDetailVo> prePurchaseOrderDetailVoList = prePurchaseTree.getPrePurchaseOrderDetailVoList();
                    prePurchaseOrderDetailVo.setPriority((byte)(prePurchaseOrderDetailVoList.size() + 1));
                    prePurchaseTree.getPrePurchaseOrderDetailVoList().add(prePurchaseOrderDetailVo);
                    prePurchaseTreeList.add(prePurchaseTree);
                }
            }
            String prePurchaseTreeJson = JSON.toJSONString(prePurchaseTreeList);
            log.info("[service] [OUT] selectTwoLevelPrePurchaseList success ");
            return prePurchaseTreeJson;
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public PrePurchaseOrder getPreEditProductInfo(Long id) {
        try {
            log.info("[service] [IN] insertPrePurchaseOrder param : id = {}", id);
            PrePurchaseOrder prePurchaseOrder = prePurchaseOrderMapper.selectByPrimaryKey(id);
            log.info("[service] [OUT] getPrePurchaseOrder success ");
            return prePurchaseOrder;
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult editPrePurchaseOrder(PrePurchaseOrderVo prePurchaseOrderVo) {
        try {
            log.info("[service] [IN] editPrePurchaseOrder param : prePurchaseOrderVo = {}", prePurchaseOrderVo.toString());
            if (prePurchaseOrderVo.getProductId() == null || prePurchaseOrderVo.getProductId() == 0) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "关联商品ID不能为空");
            }
            if (prePurchaseOrderVo.getWholeNum() == null || prePurchaseOrderVo.getWholeNum() == 0) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "整采数量不能为空");
            }
            if (prePurchaseOrderVo.getWholePrice() == null) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "整采价格不能为空");
            }
            if (prePurchaseOrderVo.getZeroPrice() == null) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "零采价格不能为空");
            }
            if (prePurchaseOrderVo.getCouldPurchaseNum() == null && prePurchaseOrderVo.getCouldPurchaseNum() == 0) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "可采数量不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getActualPicUrl())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "实拍图片不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getActualVedioUrl())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "实拍视频不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getPurchaseStartTime())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "采购开始时间不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getPurchaseEndTime())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "采购结束时间不能为空");
            }
            if (!DataValidateUtil.verifyString(prePurchaseOrderVo.getSupplierName())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "供应商名称");
            }
            PrePurchaseOrder prePurchaseOrder = new PrePurchaseOrder();
            BeanUtils.copyProperties(prePurchaseOrderVo, prePurchaseOrder);
            prePurchaseOrder.setPurchaseStartTime(DataConvertUtil.StringToDateWithFormat(prePurchaseOrderVo.getPurchaseStartTime(), CommonConstant.DATE_FORMAT));
            prePurchaseOrder.setPurchaseEndTime(DataConvertUtil.StringToDateWithFormat(prePurchaseOrderVo.getPurchaseEndTime(), CommonConstant.DATE_FORMAT));
            prePurchaseOrder.setCreateTime(null);
            prePurchaseOrderMapper.updateByPrimaryKeySelective(prePurchaseOrder);
            log.info("[service] [OUT] selectTwoLevelPrePurchaseList success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public PrePurchaseDetail getPrePurchaseDetail(Long productId) {
        try {
            log.info("[service] [IN] getPrePurchaseDetail param : productId = {}", productId);
            Date date = new Date();
            Date theDayBegin = DataConvertUtil.getTheDayBegin(date);
            Date theDayEnd = DataConvertUtil.getTheDayEnd(date);
            //设置商品基础信息
            FoundationProduct foundationProduct = foundationProductMapper.selectByPrimaryKey(productId);
            PrePurchaseDetail prePurchaseDetail = new PrePurchaseDetail();
            BeanUtils.copyProperties(foundationProduct, prePurchaseDetail);
            prePurchaseDetail.setProductId(foundationProduct.getId());
            //设置相关价格信息
            List<PrePurchaseOrder> prePurchaseOrders = prePurchaseOrderMapper.selectTheDayPrePurWithProductList(theDayBegin, theDayEnd, productId);
            //实拍图跟视频
            StringBuffer actualPicUrls = new StringBuffer();
            StringBuffer actualVedioUrls = new StringBuffer();
            int i = 0;
            byte j = 0;
            List<PrePurchaseSimpleVo> prePurchaseSimpleVoList = new ArrayList<>();
            for (PrePurchaseOrder prePurchaseOrder : prePurchaseOrders) {
                String purchasePersonId = prePurchaseOrder.getPurchasePersonId();
                FoundationSysUser foundationSysUser = foundationSysUserMapper.selectByPrimaryKey(purchasePersonId);
                PrePurchaseSimpleVo prePurchaseSimpleVo = new PrePurchaseSimpleVo();
                BeanUtils.copyProperties(prePurchaseOrder, prePurchaseSimpleVo);
                prePurchaseSimpleVo.setPrePurchaseOrderId(prePurchaseOrder.getId());
                prePurchaseSimpleVo.setPurchaseUserName(foundationSysUser.getUserName());
                prePurchaseSimpleVoList.add(prePurchaseSimpleVo);
                //拼装实拍图跟实拍视频信息
                actualPicUrls.append(prePurchaseOrder.getActualPicUrl());
                actualVedioUrls.append(prePurchaseOrder.getActualVedioUrl());
                if ( i < prePurchaseOrders.size() - 1){
                    actualPicUrls.append(",");
                    actualVedioUrls.append(",");
                }
                prePurchaseSimpleVo.setPriority(++j);

            }
            prePurchaseDetail.setPrePurchaseOrderList(prePurchaseSimpleVoList);
            prePurchaseDetail.setActualPicUrl(actualPicUrls.toString());
            prePurchaseDetail.setActualVedioUrl(actualVedioUrls.toString());
            //设置该商品昨天的预上架信息
            List<PreShelfOrder> preShelfOrderInfoList = preShelfOrderMapper.getPreShelfOrderInfo(productId);
            if (preShelfOrderInfoList.size() > 0) {
                PreShelfOrder preShelfOrder = preShelfOrderInfoList.get(0);
                prePurchaseDetail.setLimitSaleNum(preShelfOrder.getLimitSaleNum());
                prePurchaseDetail.setSingleCusLimitNum(preShelfOrder.getSingleCusLimitNum());
                prePurchaseDetail.setTitle(preShelfOrder.getTitle());
                prePurchaseDetail.setShareTitle(preShelfOrder.getShareTitle());
                prePurchaseDetail.setCommodityOrdering(preShelfOrder.getCommodityOrdering());
            }
            log.info("[service] [OUT] getPrePurchaseDetail success ");
            return prePurchaseDetail;
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult generatePreOnShelfOrder(PrePurchaseDetail purchaseDetail,String auditName) {
        try {
            log.info("[service] [IN] generatePrePurchaseOrder param : purchaseDetail = {}", purchaseDetail.toString());
            GlobalProcessionControl globalProcessionControl = globalProcessionControlMapper.getRecentProcession();

            if (!DataValidateUtil.verifyBigDecimal(purchaseDetail.getSaleMaxPrice())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "销售价不能为空或小于等于0");
            }
            if (!DataValidateUtil.verifyBigDecimal(purchaseDetail.getSaleMinPrice())) {
                return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "满整价不能为空或小于等于0");
            }
            StringBuffer preIdS = new StringBuffer();
            //1. 更新预采购订单状态
            List<PrePurchaseSimpleVo> prePurchaseOrderList = purchaseDetail.getPrePurchaseOrderList();

            for (PrePurchaseSimpleVo prePurchaseSimpleVo : prePurchaseOrderList) {
                Long prePurchaseOrderId = prePurchaseSimpleVo.getPrePurchaseOrderId();
                //审核通过
                if (prePurchaseSimpleVo.getPriority() != null) {
                    prePurchaseOrderMapper.updateStatusAndPriority(prePurchaseOrderId, OrderStatus.AUDIT.getCode(),
                            prePurchaseSimpleVo.getPriority(),
                            purchaseDetail.getRemark(),
                            auditName);
                    preIdS.append(prePurchaseSimpleVo.getPrePurchaseOrderId());
                    preIdS.append(",");
                } else {
                    prePurchaseOrderMapper.updateStatusAndPriority(prePurchaseOrderId,
                            OrderStatus.REJECT.getCode(),
                            prePurchaseSimpleVo.getPriority(),
                            purchaseDetail.getRemark(),
                            auditName);
                }
            }
            //2. 生成预上架订单
            String preIdString = BusinessUtil.killEndComma(preIdS.toString());
            PreShelfOrder preShelfOrder = new PreShelfOrder();
            BeanUtils.copyProperties(purchaseDetail, preShelfOrder);
            preShelfOrder.setPrePurchaseOrderId(preIdString);
            preShelfOrder.setRecordStatus(StatusEnum.EFFECTIVE_STATUS.getStatusCode());
            preShelfOrder.setSharePicUrl(AliConstant.DOMAIN + AliConstant.IMAGE + purchaseDetail.getSharePicUrl());
            preShelfOrder.setAuditPerson(auditName);
            preShelfOrder.setAuditTime(new Date());
            preShelfOrder.setCreateTime(new Date());
            preShelfOrder.setUpdateTime(new Date());
            preShelfOrder.setGlobalControlId(globalProcessionControl.getId());
            preShelfOrderMapper.insert(preShelfOrder);
            log.info("[service] [OUT] generatePrePurchaseOrder success ");
            return new BaseResult(ErrorCodeEnum.SUCCESS);
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult selectPreOnShelfProductList(String productName, int page, int size) {
        try {
            log.info("[service] [IN] selectPreOnShelfProductList param : page = {}, size = {}", page, size);
            Date date = new Date();
            Date theDayBegin = DataConvertUtil.getTheDayBegin(date);
            Date theDayEnd = DataConvertUtil.getTheDayEnd(date);
            PageHelper.startPage(page, size);
            List<PreOnShelfVo> preShelfOrders = preShelfOrderMapper.selectPreShelfOrderList(productName, theDayBegin, theDayEnd);
            PageInfo<PreOnShelfVo> preShelfOrderPageInfo = new PageInfo<>(preShelfOrders);
            log.info("[service] [OUT] generatePrePurchaseOrder success, size = {}, total= {} ",preShelfOrders.size(), preShelfOrderPageInfo.getTotal());
            return new BaseResult(preShelfOrderPageInfo);
        } catch (Exception e) {
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult countSalePrice(String prePurchaseOrderIds) {
        try {
            log.info("[service] [IN] countSalePrice param : prePurchaseOrderIds = {}", prePurchaseOrderIds);
            //1. 获取单位运费(每件的运费)
            ConfigCommon configInfoByCode = configCommonMapper.getConfigInfoByCode(CommonConstant.TRANSPORT_COST);
            String transportCost = configInfoByCode.getConfigValue();
            BigDecimal transportCostPrice = new BigDecimal(transportCost);
            log.info("单位运费 = {}", transportCost);
            //2. 计算加权平均采购价格
            String[] prePurchaseOrderIdArray = prePurchaseOrderIds.split(",");
            int totalPurchaseNum = 0;
            BigDecimal totalZeroMoney = new BigDecimal(0);
            BigDecimal totalWholeMoney = new BigDecimal(0);
            for (String prePurchaseOrderId : prePurchaseOrderIdArray){
                PrePurchaseOrder prePurchaseOrder = prePurchaseOrderMapper.selectByPrimaryKey(Long.parseLong(prePurchaseOrderId));
                //取数据
                Integer couldPurchaseNum = prePurchaseOrder.getCouldPurchaseNum();
                BigDecimal zeroPrice = prePurchaseOrder.getZeroPrice();
                BigDecimal wholePrice = prePurchaseOrder.getWholePrice();
                //算总成本
                totalPurchaseNum += couldPurchaseNum;
                totalZeroMoney = totalZeroMoney.add(zeroPrice.multiply(new BigDecimal(couldPurchaseNum)));
                totalWholeMoney = totalWholeMoney.add(wholePrice.multiply(new BigDecimal(couldPurchaseNum)));
            }
            BigDecimal averageZeroPrice = totalZeroMoney.divide(new BigDecimal(totalPurchaseNum));
            BigDecimal averageWholePrice = totalWholeMoney.divide(new BigDecimal(totalPurchaseNum));

            BigDecimal zeroAddTransPrice = averageZeroPrice.add(transportCostPrice);
            BigDecimal wholeAddTransPrice = averageWholePrice.add(transportCostPrice);
            log.info("计算加权平均零采价格 = {}, 整采价格 = {}", averageZeroPrice, wholeAddTransPrice);

            //3. 计算利润
            BigDecimal zeroProfitBefore = zeroAddTransPrice.multiply((new BigDecimal(0.05)));
            BigDecimal wholeProfitBefore = wholeAddTransPrice.multiply((new BigDecimal(0.05)));
            BigDecimal zeroProfitAfter = BusinessUtil.calculateMoney(zeroProfitBefore);
            BigDecimal wholeProfitAfter = BusinessUtil.calculateMoney(wholeProfitBefore);
            log.info("计算零采利润乘5%的值 = {}, 整采利润乘5%的值 = {}, 零采利润乘5%再处理后的值 = {}, 整采利润乘5%再处理后的值",
                    zeroProfitBefore, wholeProfitBefore, zeroProfitAfter,wholeProfitAfter);
            //4. 综合如上上个值
            CountPriceVo countPriceVo = new CountPriceVo();
            countPriceVo.setSaleReferMinPrice(BusinessUtil.setScale(zeroAddTransPrice.add(zeroProfitAfter)));
            countPriceVo.setSaleReferMaxPrice(BusinessUtil.setScale(wholeAddTransPrice.add(wholeProfitAfter)));
            log.info("[service] [OUT] countSalePrice success, countPriceVo = {} ", countPriceVo.toString());
            return new BaseResult(countPriceVo);
        }catch (Exception e){
            log.error("# [OUT] errorMessage: " + e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public BaseResult canBePurchased(Long productId) {
        log.info("[service] [IN] countSalePrice param : productId = {}", productId);
        GlobalProcessionControl recentProcession = globalProcessionControlMapper.getRecentProcession();
        PreOnShelfVo preOnShelfData = preShelfOrderMapper.getPreOnShelfData(recentProcession.getId(), productId);
        if (preOnShelfData != null){
            return new BaseResult(ErrorCodeEnum.DATA_ERROR.getCode(), "该商品已审核上架, 不能再进行预采购");
        }
        log.info("[service] [OUT] countSalePrice success,  ");
        return new BaseResult(ErrorCodeEnum.SUCCESS);
    }


}
